package com.android.nexttbi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.*;

import com.thoughtworks.xstream.converters.extended.ColorConverter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

	public class XMLGeneric extends ArrayAdapter<HashMap<String, String>> {
		 
	    /*
	     * Used to instantiate layout XML file into its corresponding View objects
	     */
	    private final LayoutInflater inflater;
	    private int WidhtScreen;
	    private DisplayMetrics Medidas = new DisplayMetrics();
	 
	    /*
	     * each list item layout ID
	     */
	    private final int resourceId;
	 
	    private int widthScreen = 0;
	    private Display Display;
	    public XMLGeneric(Context context, int resource, List<HashMap<String, String>> objects, int index, boolean possuiDetalhe, Display display) {
	        super(context, resource, objects);
	        this.inflater = LayoutInflater.from(context);
	        this.resourceId = resource;
	        this.widthScreen = display.getWidth();
	        Display = display;
	        display.getMetrics(Medidas);
	        setIndex(index);
	        CriaPastaImgPadrao();
	        setPossuiDetalhe(possuiDetalhe);
	    }
	    
	    public XMLGeneric(Context context, int resource, List<HashMap<String, String>> objects, int index, boolean possuiDetalhe) {
	    	super(context, resource, objects);
	        this.inflater = LayoutInflater.from(context);
	        this.resourceId = resource;
	        this.widthScreen = 0;
	        setIndex(index);
	        CriaPastaImgPadrao();
	        setPossuiDetalhe(possuiDetalhe);
	    }
	    
	    private boolean PossuiDetalhe;
	    
	    public boolean isPossuiDetalhe() {
			return PossuiDetalhe;
		}

		public void setPossuiDetalhe(boolean possuiDetalhe) {
			PossuiDetalhe = possuiDetalhe;
		}

		public boolean isChangeColumn() {
			return changeColumn;
		}

		public void setChangeColumn(boolean changeColumn) {
			this.changeColumn = changeColumn;
		}

		private boolean changeColumn;
	 
	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	 
	        //get the person from position
	    	HashMap<String, String> rel = getItem(position);
	 
	        // get a new View no matter recycling or ViewHolder FIXME
	        convertView = inflater.inflate(resourceId, parent, false);
	 
	        if (this.widthScreen < 800){
	        
		        //get all object from view
		        TextView tv1 = (TextView) convertView.findViewById(R.id.tvr1);
		        TextView tv2 = (TextView) convertView.findViewById(R.id.tvr2);
		        ImageView iv = (ImageView) convertView.findViewById(R.id.ivOpen);
		        
		        int _WVIEW = this.widthScreen;
		        int _SizeText = (int) (_WVIEW * 0.04);
		        
		        //fill the view objects according values from person object
		        tv1.setText(rel.get("col_1").trim());
		        //tv1.setTextSize(_SizeText);
		        tv1.setGravity(Gravity.CENTER_VERTICAL);
		        
		        String coluna = "col_" + (Index + 1);
		        tv2.setText(rel.get(coluna));	
		        //tv2.setTextSize(_SizeText);
		        tv2.setGravity(Gravity.CENTER_VERTICAL);
		        
		        int _WTV1 = tv1.getText().length();
		        
		        int pDesc = (int) (_WVIEW * 0.60);
		        
		        if ((_WTV1 * (_SizeText * 0.80)) > pDesc){
		        	tv1.setWidth(pDesc);
		        	tv1.setLines(2);
		        	tv2.setLines(2);
		        }
		        
		        if (rel.get("detail")==null){
		        	iv.setVisibility(View.INVISIBLE);
		        }
		        else if (rel.get("object")!=null){
		        	iv.setVisibility(View.VISIBLE);
		        }
		        else if (!isPossuiDetalhe()){
		        	iv.setVisibility(View.INVISIBLE);
		        }
		        
		        
		        String cor = rel.get("TextColor");
		        if (cor != null){
		        	if(cor.equals("greenColor")){ 
		        		tv1.setTextColor(Color.parseColor("#228B22"));
		        		tv2.setTextColor(Color.parseColor("#228B22"));
		        	}
		        	if(cor.equals("redColor")){ 
		        		tv1.setTextColor(Color.parseColor("#FF6347"));
		        		tv2.setTextColor(Color.parseColor("#FF6347"));
		        	} 
		        	if(cor.equals("blackColor")){ 
		        		tv1.setTextColor(Color.BLACK);
		        		tv2.setTextColor(Color.BLACK);
		        	} 
		        }
	        }
	        else{
	        	//get all object from view
		        TextView tvDesc = (TextView) convertView.findViewById(R.id.tvDescricaoDados);
		        TextView tvCol1 = (TextView) convertView.findViewById(R.id.tvCol1);
		        TextView tvCol2 = (TextView) convertView.findViewById(R.id.tvCol2);
		        TextView tvCol3 = (TextView) convertView.findViewById(R.id.tvCol3);
		        TextView tvCol4 = (TextView) convertView.findViewById(R.id.tvCol4);
		        ImageView iv = (ImageView) convertView.findViewById(R.id.ivOpen);
		       
		        int _WDesc = (int)(this.widthScreen*0.40);
		        int _WDados = (int)(this.widthScreen *0.14);
		        int _SizeText = 0;
		        
		        int dpi = Medidas.densityDpi;
		        if (dpi >= 240){
	        		
	        		if (WidhtScreen < 1000){
			        	_SizeText = 13;
		        	}
		        	else {
		        		_SizeText = 15;
		        	}    
	        	}
		        
		        //fill the view objects according values from person object
		        tvDesc.setText(rel.get("col_1").trim());
		        tvDesc.setGravity(Gravity.CENTER_VERTICAL);
		        
		        if (!formatTextView(tvCol4, rel.get("col_5"), _WDados, Gravity.CENTER_HORIZONTAL, true)){
		        	_WDesc += _WDados;
		        }
		        	
		        if (!formatTextView(tvCol3, rel.get("col_4"), _WDados, Gravity.CENTER_HORIZONTAL, true)){
		        	_WDesc += _WDados;
		        }
		        
		        if (!formatTextView(tvCol2, rel.get("col_3"), _WDados, Gravity.CENTER_HORIZONTAL, true)){
		        	_WDesc += _WDados;
		        }

		        if (!formatTextView(tvCol1, rel.get("col_2"), _WDados, Gravity.CENTER_HORIZONTAL, false)){
		        	_WDesc += _WDados;
		        }
		        
		        tvDesc.setWidth(_WDesc);
		        
		        if (rel.get("detail")==null){
		        	iv.setVisibility(View.INVISIBLE);
		        }
		        else if (rel.get("object")!=null){
		        	iv.setVisibility(View.VISIBLE);
		        }
		        else if (!isPossuiDetalhe()){
		        	iv.setVisibility(View.INVISIBLE);
		        }
		        
		        if (_SizeText != 0){
		        	tvDesc.setTextSize(_SizeText);
	        		tvCol1.setTextSize(_SizeText);
	        		tvCol2.setTextSize(_SizeText);
	        		tvCol3.setTextSize(_SizeText);
	        		tvCol4.setTextSize(_SizeText);
		        }
		        
		        String cor = rel.get("TextColor");
		        if (cor != null){
		        	if(cor.equals("greenColor")){ 
		        		tvDesc.setTextColor(Color.parseColor("#228B22"));
		        		tvCol1.setTextColor(Color.parseColor("#228B22"));
		        		tvCol2.setTextColor(Color.parseColor("#228B22"));
		        		tvCol3.setTextColor(Color.parseColor("#228B22"));
		        		tvCol4.setTextColor(Color.parseColor("#228B22"));
		        	}
		        	if(cor.equals("redColor")){ 
		        		tvDesc.setTextColor(Color.parseColor("#FF6347"));
		        		tvCol1.setTextColor(Color.parseColor("#FF6347"));
		        		tvCol2.setTextColor(Color.parseColor("#FF6347"));
		        		tvCol3.setTextColor(Color.parseColor("#FF6347"));
		        		tvCol4.setTextColor(Color.parseColor("#FF6347"));
		        	} 
		        	if(cor.equals("blackColor")){ 
		        		tvDesc.setTextColor(Color.BLACK);
		        		tvCol1.setTextColor(Color.BLACK);
		        		tvCol2.setTextColor(Color.BLACK);
		        		tvCol3.setTextColor(Color.BLACK);
		        		tvCol4.setTextColor(Color.BLACK);
		        	} 
		        }
	        }
	        	
	        	
	        if (position%2==0) convertView.setBackgroundColor(Color.LTGRAY);
	        else convertView.setBackgroundColor(Color.WHITE);
	 
	        return convertView;
	    }
	    
	    /*protected void _shrinkToFit(TextView tv,int wid) {

	        String t = tv.getText().toString();
	        float size = tv.getTextSize();
	        size = size / Medidas.density;
	        
	        int overWid = (int)size * t.length();
	        
	        if (overWid > wid && size >= 8) {
	        	tv.setTextSize(size - 2);
	        	_shrinkToFit(tv,wid);
	        }
	    }*/
	    
	    private boolean formatTextView(TextView tv,String valor, int size, int gravity, boolean resizeToZero){
	    	
	    	if (valor == null) valor = "";
	    	
	    	if (!valor.equals("")){
	    		tv.setText(valor);
	    		tv.setWidth(size);
	    		tv.setGravity(gravity);
	    		
	    		if (widthScreen < 1024){
		    		if (valor.length() <= 12){
		    			tv.setTextSize(14);
		    		}
		    		else{
		    			tv.setTextSize(12);
		    		}
	    		}
	    		
	    		//_shrinkToFit(tv, size);
	    		return true;
	    	}
	    	else{
	    		if (resizeToZero){
	    			tv.setWidth(0);
	    		}
	    		return false;
	    	}
	    }
	    
	    private String pathImgPadrao;
	    
	    private static String ColunaSelecionada;
	    
	    public String getColunaSelecionada() {
			return ColunaSelecionada;
		}

		public void setColunaSelecionada(String colunaSelecionada) {
			ColunaSelecionada = colunaSelecionada;
		}

		private void CriaPastaImgPadrao(){
	    	File root = Environment.getExternalStorageDirectory(); 
	    	
	    	File path= new File(root + "/Android/data/br.com.android.NexttBI", "Icones"); 
	        if (!path.exists()) {
	            path.mkdirs();
	        }
	        
	        pathImgPadrao = path.getAbsolutePath();
	    }
	    
		List<String> headers = new ArrayList<String>();
		
		SeparetedListAdapter reladapter;
	    public void CriaGrid(Document doc){
	    	
	    	// create the grid item mapping
	        String[] from = new String[] { "col_1", "col_2", "col_3","col_4","col_5","col_6","col_7","col_8","col_9","col_10"};

	        // prepare the list of all records
	        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
	                
	        HashMap<String, String> maph = new HashMap<String, String>();
	        
	    	NodeList nos = doc.getChildNodes();
	    	int col = 1;
	    	int total = 0;
	    	
	    	for (int i = 0;i <nos.getLength();i++){
	    		Node no = nos.item(i);
	    		String name = no.getNodeName();
	    		
	    		if (name.equals("Dados")) continue;
	    		
	    		if (name.equals("Grupo")){
	    			Node no2 = nos.item(i+1);
	    			headers.add(no2.getNodeName() + " - " + no2.getNodeValue());
	    			continue;
	    		}
	    		
	    		if (name.equals("Dado")){
	    			Node no3 = nos.item(i+1);
	    			
	    			while (!no3.getNodeName().equals("Dado")){
	    				String coluna = "col_" + col;
	    				
	    				maph.put(coluna, no3.getNodeValue());
	    				col++;
	    			}
	    			total = col;
	    			col = 1;
	    			fillMaps.add(maph);
	    		}
	    		
	    		if (name.equals("Total")){
	    			Node no4 = nos.item(i+1);
	    			
	    			for (int j = 0;j<total;j++){
	    				String coluna = "col_" + col;
	    				
	    				maph.put(coluna, no4.getNodeValue());
	    				col++;
	    			}
	    			col = 1;
	    			fillMaps.add(maph);
	    		}
	    		
	    	}        

	        // fill in the grid_item layout
	        Grid = fillMaps;
	    }
	    
	    private List<HashMap<String, String>> Grid = new ArrayList<HashMap<String, String>>();
		
	    public Bitmap CarregaIcone(String arquivo){
	    	
	    	try{
		    	if (arquivo.equals("") || arquivo.equals(null)) return null;
		    	
		    	Bitmap imgRetorno;
		    	
		    	String filepath = pathImgPadrao + "/"+arquivo; 
		    	
		    	BitmapDrawable bmp = new BitmapDrawable(filepath);
		    	
		    	imgRetorno = bmp.getBitmap();
		    	
		    	if (imgRetorno !=(null)){
		    		return imgRetorno;
		    	}
		    	else{
		    		BaixarIcone(arquivo, filepath);
		    		imgRetorno = CarregaIcone(arquivo);
		        	return imgRetorno;
		    	}
	    	}
	    	catch (Exception e){
	    		return null;
	    	}
	    }
	    
	    public void BaixarIcone(String arquivo, String desfilepath){
	    	try {
	    		String src = "/"+arquivo;  
	            URL url = new URL(src);
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setDoInput(true);
	            connection.connect();
	            InputStream input = connection.getInputStream();
	            Bitmap myBitmap = BitmapFactory.decodeStream(input);
	            
	            FileOutputStream desFileStream = new FileOutputStream(desfilepath);
	            
	            myBitmap.compress(CompressFormat.PNG, 90, desFileStream);
	            desFileStream.flush();
	            desFileStream.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	            Log.e("Exception",e.getMessage());
	        }
	    }
	    
	    public static Bitmap getBitmapFromURL(String src) {
	        try {
	            URL url = new URL(src);
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setDoInput(true);
	            connection.connect();
	            InputStream input = connection.getInputStream();
	            Bitmap myBitmap = BitmapFactory.decodeStream(input);
	            return myBitmap;
	        } catch (Exception e) {
	            e.printStackTrace();
	            Log.e("Exception",e.getMessage());
	            return null;
	        }
	    }
	    
	    private int Index;
	    
	    public int getIndex() {
			return Index;
		}

		public void setIndex(int index) {
			Index = index;
		}
	}
	 
